const axios = require("axios");

// 生成实时时间
const nowTime = function getTime() {
    let date = new Date();
    Y = date.getFullYear() + '-';
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    D = date.getDate() + ' ';
    h = date.getHours() + ':';
    m = date.getMinutes() + ':';
    s = date.getSeconds();
    return (Y + M + D + h + m + s)
}
// 随机数
function num() {
    return Math.round(Math.random() * 10)
}
// 自制学生ID
const getStuId = function getStuId() {
    let date = new Date();
    Y = date.getFullYear() + '-';
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    D = date.getDate();
    return `${Y + M + D}-${num()}${num()}${num()}${num()}-${num()}${num()}${num()}${num()}`
}
// 一步检测是否传了必须值
const emptyData = function (objName, keyName) {
    keyName.forEach(keyname => {
        objName[keyname] = objName[keyname] ? objName[keyname] : ""
    })
    return objName
}
// 获得课时数据
const getclasshourData = async () => {
    const res = await axios({
        method: "get",
        url: "http://localhost:3004/classhour/list",
    })
    return res.data.total
}
// 操作自动添加到日志
const postLogData = async (title) => {
    const res = await axios({
        method: "post",
        url: "http://localhost:3004/opalog/save",
        data:{
            log:title,
            name:"admin",
            ip:myHost() 
        }
    })
}
// 筛选时间区间的数据
const fileterTime = function (data, { startTime, endTime, page }) {
    let arr = []
    data.forEach(bn => {
        if (startTime < bn.uploadTime && bn.uploadTime < endTime) {
            arr.push(bn)
        }
    })
    const total = arr.length
    if (page) {
        arr = arr.slice((page * 10 - 10), (page * 10 ))
    }else{
        arr = arr.slice(0, 10)
    }
    console.log({arr,total});
    return {arr,total}
}
// 获取本机IP
const os = require('os');
///获取本机ip/// 
const myHost =function getIPAdress() {
    var interfaces = os.networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                return alias.address;
            }
        }
    }
}


module.exports = { nowTime, getStuId, emptyData, getclasshourData, fileterTime,myHost,postLogData }